<!-- 管理员页面 -->
<template>
    <div>
        <el-row>
            <el-col :span="24">
                <div class="grid-content">
                    <el-input class="m-2" v-model="data.username" placeholder="请输入管理员名称" clearable />
                    <el-button type="primary" :icon="Search" @click="init">查找</el-button>
                    <el-button type="primary" :icon="Edit" @click="handleAdd"
                        v-permission="'sys:admin:create'">添加</el-button>
                </div>
            </el-col>
        </el-row>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="id" label="管理员ID" />
            <el-table-column prop="username" label="管理员名称" />
            <el-table-column prop="realname" label="真实姓名" />
            <el-table-column prop="phone" label="电话" />
            <el-table-column label="管理员角色">
                <template #default="scope">
                    <template v-for="item in scope.row.roleIds" :key="item">
                        <el-tag>
                            {{ handleRoule(item) }}
                        </el-tag>
                    </template>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button type="primary" @click="handleEdit(scope.$index, scope.row)"
                        v-permission="'sys:admin:edit'">
                        修改
                    </el-button>
                    <el-button type="danger" @click="handleDelete(scope.$index, scope.row)"
                        v-permission="'sys:admin:delete'">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <Pagination v-bind="pagination" @page-change="handlePageChange" /><!--分页器-->
        <!-- 修改&添加弹框 -->
        <el-dialog v-model="dialogFormVisible" width="600px" :title="form.state == 1 ? '创建' : '编辑'" destroy-on-close>
            <el-form :model="form" label-position="right" label-width="80px" ref="ruleFormRef">
                <el-form-item label="用户名" prop="data.username" :rules="[{ required: true, message: '用户名不能为空' }]">
                    <el-input v-model="form.data.username" autocomplete="off" :disabled="form.state == 0" />
                </el-form-item>
                <el-form-item label="密码" prop="data.password" v-if="form.state != 0"
                    :rules="[{ required: true, message: '密码不能为空' }]">
                    <el-input v-model="form.data.password" autocomplete="off" />
                </el-form-item>
                <el-form-item label="手机号" prop="data.phone" :rules="[{ required: true, message: '手机号码不能为空' },
                {
                    required: true, message: '手机号码格式错误',
                    pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
                }]">
                    <el-input v-model="form.data.phone" autocomplete="off" />
                </el-form-item>
                <el-form-item label="真实姓名" prop="data.realname" :rules="[{ required: true, message: '真实姓名不能为空' },
                { required: true, message: '请输入汉字且长度在10个汉字之间', pattern: /^[\一-\龥]{0,10}$/ }]">
                    <el-input v-model="form.data.realname" autocomplete="off" />
                </el-form-item>
                <el-form-item label="角色" prop="data.roleIds"
                    :rules="form.state != 1 ? [{ required: true, message: '角色不能为空' }] : []">
                    <el-select v-model="form.data.roleIds" placeholder="请选择角色" multiple :reserve-keyword="false">
                        <el-option v-for="item in adminRole" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="determine(ruleFormRef)">
                        {{ form.state == 1 ? '新增' : '修改' }}
                    </el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from "vue";
import { Search, Edit } from '@element-plus/icons-vue';//图标 
import { get, post } from "@/utils/http"; //封装的axios请求方式
import { ElMessage, ElMessageBox } from 'element-plus'//提示信息
import type { FormInstance } from 'element-plus'//form的数据类型
import { PaginationClass } from "#/index";//分页数据类型
import { AdminUserClass } from "#/index";//管理员数据类型

const ruleFormRef = ref<FormInstance>()//操作form节点
const pagination = ref(new PaginationClass())//分页数据
const tableData = ref([]) //表格数据
const adminRole = ref(<TypeAdminRole[]>[]) //管理员角色数据
const dialogFormVisible = ref(false)//权限弹框是否显示

let data = ref({//请求传递的数据
    _gp: 'admin',
    _mt: 'list',
    username: '',//管理员名称搜索
    page: 1,//当前的页数
    limit: 10//每页显示条数
})

let form = ref({
    state: 0, //0:修改 1:新增
    data: new AdminUserClass()
})

onMounted(() => {
    init()
})

// 初始化数据
function init() {
    post(data.value).then((res) => {
        console.log(res);
        let { data } = res
        tableData.value = data.items;//表格数据赋值
        pagination.value.total = data.total;//总页数赋值
    })
    data.value.username = ''//查找完成后清空input框的值
    infoRoule()
}

// 初始化管理员角色数据
function infoRoule() {
    post({ _gp: 'admin.role', _mt: 'options' }).then((res) => {
        console.log(res);
        let { data } = res
        adminRole.value = data
    })
}

// 处理管理员角色数据
function handleRoule(rouIds: any) {
    for (let v of adminRole.value) {
        if (v.value == rouIds) {
            return rouIds = v.label
        }
    }
    return rouIds = ''
}

// 添加
function handleAdd() {
    dialogFormVisible.value = true;
    form.value.state = 1;//添加时状态为1
    ruleFormRef.value?.resetFields();//重置表单初始值
    form.value.data = (<AdminUserClass>{});
}

// 修改
function handleEdit(index: number, row: any) {
    dialogFormVisible.value = true;
    form.value.state = 0;//修改时状态为0
    ruleFormRef.value?.resetFields();//重置表单初始值
    form.value.data = { ...row };
}

// 弹框确定
function determine(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            post({
                _gp: 'admin',
                _mt: form.value.state == 1 ? 'create' : 'edit',
                adminDTO: JSON.stringify({ ...form.value.data })
            }).then((res) => {
                console.log(res);
                let { errmsg, errno } = res;
                200 == errno ? ElMessage.success(form.value.state == 1 ? '添加成功!' : '修改成功!') : ElMessage.error(errmsg);
                dialogFormVisible.value = false;//隐藏弹框
                init()
            })
        } else {
            return false
        }
    })

}

// 删除
function handleDelete(index: number, row: any) {
    ElMessageBox.confirm(
        '确定要删除吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    ).then(() => {
        get({ _gp: 'admin', _mt: 'delete', id: row.id }).then((res) => {
            console.log(res);
            let { errmsg, errno } = res
            200 == errno ? ElMessage.success('删除已完成') : ElMessage.error(errmsg)
            init()
        })
    }).catch(() => {
        ElMessage.info('删除已取消')
    })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

// 分页组件里的数据赋值
function handlePageChange(v: any) {
    data.value.page = v.page
    data.value.limit = v.limit
    init()
}
</script>
<style lang="less" scoped>
.el-row {
    margin-bottom: 20px;
}

.grid-content {
    .m-2 {
        width: 350px;
    }

    .el-button {
        margin-left: 10px;
    }
}

.el-form {
    width: 450px;
    margin: auto;
}

.el-tag {
    margin: 5px;
}
</style>
